//
//  UITextView-Extension.swift
//  表情键盘
//
//  Created by 叶子韬韬 on 2017/5/12.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import UIKit
extension UITextView{
    func insertEmoticon(emoticon:Emoticon)  {
        //1 空白表情
        if emoticon.isEmpty {
            return
        }
        
        //2 删除按钮
        if emoticon.isRemove {
            deleteBackward()  //删除光标前一个字符
            return
        }
        //3 emoji
        if emoticon.emojiCode != nil {
            
            //获取光标所在的位置
            let textRang = selectedTextRange!
            
            replace(textRang, withText: emoticon.emojiCode!)
            
            return
        }
        //4 普通表情图文混排
        //创建属性字符串
        let attachment = EmoticonAttachment()
        attachment.chs = emoticon.chs
        attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        attachment.bounds = CGRect.init(x: 0, y: -4, width: font!.lineHeight, height: font!.lineHeight)
        let attImageStr = NSAttributedString(attachment: attachment)
        
        //创建可变的属性字符串
        let attMStr = NSMutableAttributedString(attributedString: attributedText)
        
        let rang = selectedRange
        
        attMStr.replaceCharacters(in: rang, with: attImageStr)
        
        attributedText = attMStr
        
        //将文字重置
        font = UIFont.systemFont(ofSize: 17)
        
        //设置光标设置原来位置+1
       selectedRange = NSRange.init(location: rang.location+1, length: 0)
        

    }
    
    func getEmoticonString() -> String {
        
        //获取属性字符串
        let attMStr = NSMutableAttributedString(attributedString: attributedText)
        
        //遍历属性字符串
        let rang = NSRange(location: 0, length: attMStr.length)
        attMStr.enumerateAttributes(in: rang, options: []) { (dict, rang, _) in
          
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment{
                attMStr.replaceCharacters(in: rang, with: attachment.chs!)
            }
            
           
            
        }
        

        return attMStr.string
    }
}
